package com.znf.config;

import com.znf.base.support.JsonAuthenticationEntryPoint;
import com.znf.util.JwtUtils;
import lombok.Data;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.configuration.AuthenticationConfiguration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

import javax.annotation.Resource;

@Data
@Configuration
@EnableWebSecurity
public class SecurityConfig {

    @Resource
    private AuthProperties authProperties;

    /**
     * securty核心过滤链
     *
     * @param http
     * @return
     * @throws Exception
     */
    @Bean
    public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
        // 关闭csrf
        http.csrf().disable()
                // 禁用session
                .sessionManagement(sessionManagement -> sessionManagement.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
                // 配置拦截规则
                .authorizeRequests(authorize -> authorize.antMatchers(authProperties.getIgnoreUrls().toArray(new String[0])).permitAll().anyRequest().authenticated())
                // 异常处理
                .exceptionHandling(handler -> {
                    handler.authenticationEntryPoint(new JsonAuthenticationEntryPoint());
                    handler.accessDeniedHandler(null);
                })
                .addFilterBefore(jwtAuthenticationFilter(), UsernamePasswordAuthenticationFilter.class)
        ;
        return http.build();
    }

    @Bean
    public JwtAuthenticationFilter jwtAuthenticationFilter() {
        return new JwtAuthenticationFilter(jwtUtils(authProperties));
    }

    @Bean
    public JwtUtils jwtUtils(AuthProperties authProperties) {
        return new JwtUtils(authProperties.getJwt());
    }

    /**
     * 密码加密器
     *
     * @return 密码加密器
     */
    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }

    /**
     * 自定义认证管理器
     */
    @Bean
    public AuthenticationManager authenticationManager(AuthenticationConfiguration authenticationConfiguration) throws Exception {
        return authenticationConfiguration.getAuthenticationManager();
    }
}
